package MySQL::Query::Extract::GROUPBY;

use strict;
use warnings;

use base qw(MySQL::Query::Extract);
use Carp;

my $token_class = 'DBIx::MyParsePP::Token';
my $rule_class = 'DBIx::MyParsePP::Rule';

sub parse_tree     { return shift->tree->tree }
sub tokens         { return shift->tree->tokens(@_) }

sub process {
      my ($self , $sel , $extract) = @_;
      
      my $groupby_tree = $self->parse_tree->getGroupBy(); 
      $groupby_tree = $groupby_tree->shrink(); #oh, godness :)
      if ($groupby_tree) {
      	    my $data = ($groupby_tree->children())[2]; #we need only this
	    
	    if ($data->[0] ne 'group_list') {
		 $data = [$data];
	    }
	    
            for (my $i = 0; $i <= $#{$data}; $i++) { #search for our table
		  if (ref $data->[$i] eq $rule_class) {
			if (
			    $self->cmp_names($data->[$i]->[1]->value() , $extract)
			) {
			      my $groupby_temp = $data->[$i]->[1]->value() . '.' . $data->[$i]->[3]->value(); # improve SQL::Builder::GroupBy and refactor
			      $sel->groupby->list_push($groupby_temp);
			}
		  } elsif (ref $data->[$i] eq $token_class) {
			my $iterator = $sel->cols->children; 
			if ($iterator) {
			      while($iterator->pull)  {
				    my $current_object = $iterator->current;
				    if (
					  $current_object->alias &&
					  $current_object->alias eq $data->[$i]->value
				    ) {
					  # add it to that $sel
					  $sel->groupby->list_push($data->[$i]->value);
				    }
			      }
			}
		  } 
	    }
      }
}

1;

=head1 NAME

MySQL::Query::Extract::GROUPBY

=head1 SYNOPSIS

=head1 DESCRIPTION

=head1 METHODS

=head2 new()

=head2 process()